import React, { Component } from "react";
import PubSub from "pubsub-js";
import Son from "./Son";
export default class Far extends Component {
  //假设app订阅接收数据 ,在对应话题发布的时候会触发回调
  componentDidMount() {
    // PubSub.subscribe('话题'，回调函数)
    this.token1 = PubSub.subscribe("fp", (topic, data) => {
      // topic是话题
      // data是接收的数据
      console.log("far接收son发布的信息", topic, data);
    });
    this.token2 = PubSub.subscribe("appfb", (topic, data) => {
      console.log("app发布far接收", topic, data);
    });
  }

  // 组件卸载的时候取消订阅,（这是应该写在这里的）
  componentWillUnmount() {
    PubSub.unsubscribe(this.token1);
    PubSub.unsubscribe(this.token2);
  }

  render() {
    return (
      <div>
        far
        <Son></Son>
        <button
          onClick={() => {
            PubSub.unsubscribe(this.token1);
          }}
        >
          清除指定的订阅PubSub.unsubscribe(token);
        </button>
        <button
          onClick={() => {
            PubSub.unsubscribe("appfb");
          }}
        >
          清除指定话题的订阅PubSub.unsubscribe(话题);
        </button>
        <button
          onClick={() => {
            PubSub.clearAllSubscriptions();
          }}
        >
          取消所有订阅PubSub.clearAllSubscriptions();
        </button>
      </div>
    );
  }
}
